import warnings
warnings.filterwarnings("ignore")
import os
import argparse

import torch.distributed as dist
import torch.nn.functional as F
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import yaml

import test  # import test.py to get mAP after each epoch
from models.yolo import Model
from utils.datasets import *
from utils.wiky_datasets_ver3 import *
from utils.utils import *

mixed_precision = False
try:  # Mixed precision training https://github.com/NVIDIA/apex
    from apex import amp
except:
    # print('Apex recommended for faster mixed precision training: https://github.com/NVIDIA/apex')
    mixed_precision = False  # not installed



# Hyperparameters
hyp = {'lr0': 0.001,  # initial learning rate (SGD=1E-2, Adam=1E-3)
       'momentum': 0.99,  # SGD momentum
       'weight_decay': 5e-4,  # optimizer weight decay
       'giou': 0.05,  # giou loss gain
       'cls': 0.58,  # cls loss gain
       'cls_pw': 1.0,  # cls BCELoss positive_weight
       'obj':4.0,  # obj loss gain (*=img_size/320 if img_size != 320)
       'obj_pw': 1.0,  # obj BCELoss positive_weight
       'iou_t': 0.10,  # iou training threshold
       'anchor_t': 4.0,  # anchor-multiple threshold
       'fl_gamma': 0.0,  # focal loss gamma (efficientDet default is gamma=1.5)
       'hsv_h': 0.014,  # image HSV-Hue augmentation (fraction)
       'hsv_s': 0.68,  # image HSV-Saturation augmentation (fraction)
       'hsv_v': 0.36,  # image HSV-Value augmentation (fraction)
       'degrees': 0.0,  # image rotation (+/- deg)
       'translate': 0.0,  # image translation (+/- fraction)
       'scale': 0.5,  # image scale (+/- gain)
       'shear': 0.0}  # image shear (+/- deg)

def train(hyp):

    print(hyp)

    # Overwrite hyp with hyp*.txt (optional)
    f = glob.glob('hyp*.txt')
    if f:
        print('Using %s' % f[0])
        for k, v in zip(hyp.keys(), np.loadtxt(f[0])):
            hyp[k] = v

    # Print focal loss if gamma > 0

    
    if hyp['fl_gamma']>0:
        hyp['fl_gamma'] =  opt.fl_gamma
        print('Attetnion!!! Using FocalLoss(gamma=%g)' % hyp['fl_gamma'])


    wdir = opt.name + os.sep  # weights dir

    #if no exist, create it
    if not os.path.exists(wdir):
        os.makedirs(wdir, 0o777, exist_ok=True)

    last = wdir + 'last.pt'
    best = wdir + 'best.pt'
    epoch_model = wdir + "epoch_"
    results_file = wdir + 'results.txt'

    # 写一个opt.txt 按照 定义先后顺序 排列 遇到，就切行
    with open(wdir + 'opt.txt', 'w') as f:
        for k, v in opt.__dict__.items():
            if k == 'opt':
                print(v)
                f.write('%s\n' % v)
            else:
                print('%s: %s' % (k, v))
                f.write('%s: %s\n' % (k, v))

    # 也在opt.txt 继续写入 hyp
    with open(wdir + 'opt.txt', 'a') as f:
        f.write('\n\n*********hyp*********\n')
        for k, v in hyp.items():
            print('%s: %s' % (k, v))
            f.write('%s: %s\n' % (k, v))
    



    epochs = opt.epochs  # 300
    batch_size = opt.batch_size  # 64
    weights = opt.weights  # initial training weights

    # Configure
    init_seeds(1)
    with open(opt.data) as f:
        data_dict = yaml.load(f, Loader=yaml.FullLoader)  # model dict
    train_path = data_dict['train']
    test_path = data_dict['val']
    nc = 1 if opt.single_cls else int(data_dict['nc'])  # number of classes

    # Remove previous results
    for f in glob.glob('*_batch*.jpg') + glob.glob(results_file):
        os.remove(f)

    # Create model
    model = Model(opt.cfg).to(device)
    assert model.md['nc'] == nc, '%s nc=%g classes but %s nc=%g classes' % (opt.data, nc, opt.cfg, model.md['nc'])

    print (model.stride)
    
    # Image sizes
    gs = int(max(model.stride))  # grid size (max stride)
    if any(x % gs != 0 for x in opt.img_size):
        print('WARNING: --img-size %g,%g must be multiple of %s max stride %g' % (*opt.img_size, opt.cfg, gs))
    imgsz, imgsz_test = [make_divisible(x, gs) for x in opt.img_size]  # image sizes (train, test)

    # Optimizer
    nbs = 64  # nominal batch size
    accumulate = max(round(nbs / batch_size), 1)  # accumulate loss before optimizing
    hyp['weight_decay'] *= batch_size * accumulate / nbs  # scale weight_decay
    pg0, pg1, pg2 = [], [], []  # optimizer parameter groups
    for k, v in model.named_parameters():
        if v.requires_grad:
            if '.bias' in k:
                pg2.append(v)  # biases
            elif '.weight' in k and '.bn' not in k:
                pg1.append(v)  # apply weight decay
            else:
                pg0.append(v)  # all else

    optimizer = optim.Adam(pg0, lr=hyp['lr0']) if opt.adam else \
        optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
    optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']})  # add pg1 with weight_decay
    optimizer.add_param_group({'params': pg2})  # add pg2 (biases)
    print('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
    del pg0, pg1, pg2

    # Load Model
    # google_utils.attempt_download(weights)
    start_epoch, best_fitness = 0, 0.0
    if weights.endswith('.pt')and os.path.exists(weights):  # pytorch format:  # pytorch format
        ckpt = torch.load(weights, map_location=device)  # load checkpoint
        print("------------------------------------------>>> start load load model !!!")
        # load model
        try:
            ckpt['model'] = \
                {k: v for k, v in ckpt['model'].state_dict().items() if model.state_dict()[k].numel() == v.numel()}
            model.load_state_dict(ckpt['model'], strict=False)
            print("------------------------------------------>>> success load model !!!")
        except KeyError as e:
            s = "%s is not compatible with %s. Specify --weights '' or specify a --cfg compatible with %s." \
                % (opt.weights, opt.cfg, opt.weights)
            raise KeyError(s) from e

        # load optimizer
        if ckpt['optimizer'] is not None:
            optimizer.load_state_dict(ckpt['optimizer'])
            best_fitness = ckpt['best_fitness']

        # load results
        if ckpt.get('training_results') is not None:
            with open(results_file, 'w') as file:
                file.write(ckpt['training_results'])  # write results.txt

        start_epoch = ckpt['epoch'] + 1
        del ckpt
    else:
        print('no checkpoint found, directlty train...\n')

    # Mixed precision training https://github.com/NVIDIA/apex
    if mixed_precision:
        model, optimizer = amp.initialize(model, optimizer, opt_level='O1', verbosity=0)

    # Scheduler https://arxiv.org/pdf/1812.01187.pdf
    lf = lambda x: (((1 + math.cos(x * math.pi / epochs)) / 2) ** 1.0) * 0.9 + 0.1  # cosine
    scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
    scheduler.last_epoch = start_epoch - 1  # do not move

    dataset  = BigHandDetectionDataset_Dual(path = '/home_ssd/lhc/hand_detect_v3',
                                        is_train= True,
                                        event_subdir = opt.event_subdir,
                                        event_needed = opt.eve_bin_needed,
   
                                        train_step = opt.train_step,)
 
    if opt.fl_gamma !=0: # 无GT的负样本

        dataset_negative_sample = BigHandDetectionDataset_Dual(path = '/home_ssd/lhc/hand_detect_v3_msample',
                                        is_train= True,
                                        event_subdir = opt.event_subdir,
                                        event_needed = opt.eve_bin_needed,
   
                                        train_step = 1,)
        
        dataset_1 = ConcatDataset([dataset, dataset_negative_sample])

    else:
        dataset_1 = dataset


    # mlc = np.concatenate(dataset.labels, 0)[:, 0].max()  # max label class
    # assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Correct your labels or your model.' % (mlc, nc, opt.cfg)

    # Dataloader
    batch_size = min(batch_size, len(dataset_1))
    nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 12])  # number of workers
    dataloader = torch.utils.data.DataLoader(dataset_1,
                                             batch_size=batch_size,
                                             num_workers=nw,
                                             shuffle= True,  # Shuffle=True unless rectangular training is used
                                             # but my all dataset is rectangular720x1280
                                             pin_memory=True,
                                             collate_fn=dataset.collate_fn)



    # Model parameters
    hyp['cls'] *= nc / 80.  # scale coco-tuned hyp['cls'] to current dataset
    model.nc = nc  # attach number of classes to model
    model.hyp = hyp  # attach hyperparameters to model
    model.gr = 1.0  # giou loss ratio (obj_loss = 1.0 or giou)

    # 这里设置为所有权重均分且归一化 比如 4个 就是 [0.25,0.25,0.25,0.25]

    model.class_weights = torch.ones(model.nc, device=device) / model.nc

    # model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device)  # attach class weights
    model.names = data_dict['names']

    # class frequency
    # labels = np.concatenate(dataset.labels, 0)
    # c = torch.tensor(labels[:, 0])  # classes

    # Exponential moving average
    ema = torch_utils.ModelEMA(model)

    # Start training
    t0 = time.time()
    nb = len(dataloader)  # number of batches
    n_burn = max(3 * nb, 1e3)  # burn-in iterations, max(3 epochs, 1k iterations)
    maps = np.zeros(nc)  # mAP per class
    results = (0, 0, 0, 0, 0, 0, 0)  # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification'
    print('Image sizes %g train, %g test' % (imgsz, imgsz_test))
    print('Using %g dataloader workers' % nw)
    print('Starting training for %g epochs...' % epochs)
    # torch.autograd.set_detect_anomaly(True)

    C = opt.event_count_threshlod

    for epoch in range(start_epoch, epochs):  # epoch ------------------------------------------------------------------
        model.train()

        # Update image weights (optional)
        # if dataset.image_weights:
        #     w = model.class_weights.cpu().numpy() * (1 - maps) ** 2  # class weights
        #     image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w)
        #     dataset.indices = random.choices(range(dataset.n), weights=image_weights, k=dataset.n)  # rand weighted idx

        mloss = torch.zeros(4, device=device)  # mean losses
        print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size'))
        pbar = tqdm(enumerate(dataloader), total=nb)  # progress bar

        for i, (imgs, eves, targets, paths) in pbar:  # batch -------------------------------------------------------------
            ni = i + nb * epoch  # number integrated batches (since train start)

            # Burn-in
            if ni <= n_burn:
                xi = [0, n_burn]  # x interp
                # model.gr = np.interp(ni, xi, [0.0, 1.0])  # giou loss ratio (obj_loss = 1.0 or giou)
                accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
                for j, x in enumerate(optimizer.param_groups):
                    # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
                    x['lr'] = np.interp(ni, xi, [0.1 if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
                    if 'momentum' in x:
                        x['momentum'] = np.interp(ni, xi, [0.9, hyp['momentum']])

            # Multi-scale
            if opt.multi_scale:
                sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs  # size
                sf = sz / max(imgs.shape[2:])  # scale factor
                if sf != 1:
                    ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]]  # new shape (stretched to gs-multiple)
                    imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)

            if opt.train_type == "image":
                input_imgs = imgs.to(device).float() 
                
            else:
                input_imgs = eves.to(device).float() 

                if opt.event_subdir[-10:] =="_count_raw":
                    input_imgs = torch.where(input_imgs >= 128 + C, torch.tensor(200.0).to(device), input_imgs)
                    input_imgs = torch.where(input_imgs <= 128 - C, torch.tensor(100.0).to(device), input_imgs)
                    input_imgs = torch.where((input_imgs !=200) & (input_imgs!=100), torch.tensor(0.0).to(device), input_imgs)  

            show_imgs =   input_imgs[:,-3:,:,:].cpu().numpy()  

            input_imgs /=  255.0  

            # Forward
            pred = model(input_imgs)

            # Loss
            loss, loss_items = compute_loss(pred, targets.to(device), model)
            if not torch.isfinite(loss):
                print('WARNING: non-finite loss, ending training ', loss_items)
                return results

            # Backward
            if mixed_precision:
                with amp.scale_loss(loss, optimizer) as scaled_loss:
                    scaled_loss.backward()
            else:
                loss.backward()

            # Optimize
            if ni % accumulate == 0:
                optimizer.step()
                optimizer.zero_grad()
                ema.update(model)
 
            mloss = (mloss * i + loss_items) / (i + 1)  # update mean losses
            mem = '%.3gG' % (torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0)  # (GB)
            s = ('%10s' * 2 + '%10.4g' * 6) % (
                '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], input_imgs.shape[-1])
            pbar.set_description(s)

            # Plot
            if i < 3:
                print("------------------------------------------------------->>>   plot")

                new_temporal = './{}/temporal'.format(opt.name)

                os.makedirs(new_temporal, 0o777,exist_ok=True)

                f = '{}/epoch_{}_train_batch_{}.jpg'.format(new_temporal,epoch,i)  # filename
                res = plot_images(images= show_imgs,
                                  targets=targets, paths=paths, fname=f)

            # end batch ------------------------------------------------------------------------------------------------

        # Scheduler
        scheduler.step()

        # mAP
        ema.update_attr(model)
        final_epoch = epoch + 1 == epochs

        # Write
        with open(results_file, 'a') as f:
            f.write(s + '%10.4g' * 7 % results + '\n')  # P, R, mAP, F1, test_losses=(GIoU, obj, cls)
        if len(opt.name) and opt.bucket:
            os.system('gsutil cp results.txt gs://%s/results/results%s.txt' % (opt.bucket, opt.name))

        # Update best mAP
        fi = fitness(np.array(results).reshape(1, -1))  # fitness_i = weighted combination of [P, R, mAP, F1]
        if fi > best_fitness:
            best_fitness = fi

        # Save model
        save = (not opt.nosave) or (final_epoch and not opt.evolve)
        if save:
            with open(results_file, 'r') as f:  # create checkpoint
                ckpt = {'epoch': epoch,
                        'best_fitness': best_fitness,
                        'training_results': f.read(),
                        'model': ema.ema.module if hasattr(model, 'module') else ema.ema,
                        'optimizer': None if final_epoch else optimizer.state_dict()}

            # Save last, best and delete
            torch.save(ckpt, last)
            torch.save(ckpt,epoch_model+"{}.pt".format(epoch))
            if (best_fitness == fi) and not final_epoch:
                torch.save(ckpt, best)
            del ckpt

        # end epoch ----------------------------------------------------------------------------------------------------
    # end training

    with open(results_file, 'a') as f:
        f.write(( '%10s' * 8 +'\n') % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size')) 



    print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
    # dist.destroy_process_group() if torch.cuda.device_count() > 1 else None
    torch.cuda.empty_cache()
    return results


if __name__ == '__main__':
    parser = argparse.ArgumentParser()


    train_type  = "image" # "image" 

    event_subdir = f"event_img_120fps"#'event_img_120fps_count_raw'#

    eve_bin_needed = -1 if train_type  != "image" else 0 # 取其他数字则为全部； -1时取事件的label, 其他则为img label

    train_step = 5

    event_count_threshlod = 1

    focal_loss = -1.0 # 取 -1时引入负样本 但不进行focal loss; 取0取消负样本; 取正数引入负样本并进行focal loss

    epochs = 15

    batch_size = 16

    device_str = '0'

    weights = 'models/yolov5s.pt'

    if train_type == "image":
        input_name = f'hand_v5s_{time.strftime("%m%d_%H%M")}_img'
        
    elif train_type == "event" and event_subdir[-10:]=="_count_raw":
        input_name = f'hand_v5s_{time.strftime("%m%d_%H%M")}_eve_c_{event_subdir[-16:-10]}'
    else:
        input_name = f'hand_v5s_{time.strftime("%m%d_%H%M")}_eve_{event_subdir[-6:]}'

    parser.add_argument('--version', type=str, default="3.1 # train with event processed into images")

    parser.add_argument('--event_subdir', type=str, default=event_subdir)
    parser.add_argument('--event_count_threshlod',type=int, default=event_count_threshlod)
    parser.add_argument('--train_type', default= train_type, help = "you choose which type")
    parser.add_argument('--eve_bin_needed', default= eve_bin_needed, help = "you choose which type")

    parser.add_argument('--train_step', default= train_step, help = "you choose which type")

    parser.add_argument('--name', default=input_name, help='the folder which saves the results')

    parser.add_argument('--fl_gamma',type = float,  default=focal_loss, help='gamma for focal loss')

    parser.add_argument('--epochs', type=int, default=epochs)
    parser.add_argument('--batch-size', type=int, default=batch_size)
    parser.add_argument('--cfg', type=str, default='models/yaml/wiky_yolov5s.yaml', help='*.cfg path')
    parser.add_argument('--weights', type=str, default=weights, help='initial weights path')
    
    parser.add_argument('--adam', default=True, help='use adam optimizer')
    
    parser.add_argument('--device', default=device_str, help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
   
    parser.add_argument('--data', type=str, default='data/wiky_hand_ver2.yaml', help='*.data path')

    parser.add_argument('--img-size', nargs='+', type=int, default=[1280,1280], help='train,test sizes')

    parser.add_argument('--rect', default=True, help='rectangular training')#矩形填充

    parser.add_argument('--resume', default=False, help='resume training from last.pt')
    parser.add_argument('--nosave', default=False, help='only save final checkpoint')
    parser.add_argument('--notest', default=False, help='only test final epoch')

    parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
    parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
    parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
    
    
    parser.add_argument('--multi-scale', default=False, help='vary img-size +/- 50%')
    parser.add_argument('--single-cls', default=False, help='train as single-class dataset')

    opt = parser.parse_args()

    # opt.weights = last if opt.resume else opt.weights
    last = opt.weights.replace('.pt', 'last.pt')
    opt.weights = last if opt.resume else opt.weights


    opt.cfg = glob.glob('./**/' + opt.cfg, recursive=True)[0]  # find file
    opt.data = glob.glob('./**/' + opt.data, recursive=True)[0]  # find file
    print(opt)
    opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size)))  # extend to 2 sizes (train, test)
    device = torch_utils.select_device(opt.device, apex=mixed_precision, batch_size=opt.batch_size)
    # check_git_status()
    if device.type == 'cpu':
        mixed_precision = False

    # Train
    if not opt.evolve:
        train(hyp)

    # Evolve hyperparameters (optional)
    else:
        pass
